<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2023/7/5
 * Time: 14:41
 */

namespace app\api\controller;

use pay\Wxservicer;
use think\Db;

class Shou extends Base
{
    public $user_id;
    public $create_time;
    public $page;

    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }

    /*
     * 用户权限
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserRule(){
        $rule = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_shou_rule, user_serve_rule, user_fp_serve_rule, user_recharge_price, user_dj_rule')
            ->find();
        return json(['status' => 200, 'msg' => $rule]);
    }

    /**
     * 充值项目
     * type    1 入系统   2 快递费   3 特惠商品   4 家大业大   5 补货款
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function rechargeProject(){
        $type = input('type') ? input('type') : 0;
        $where['status'] = 1;
        if($type == 1){
            $where['id'] = ['IN', [1, 7]];
        }elseif ($type == 2){
            $where['id'] = 6;
        }elseif ($type == 3){
            $where['id'] = 4;
        }elseif($type == 4){
            $where['id'] = 5;
        }elseif ($type == 5){
            $where['id'] = 2;
        }
        $data = Db::table('up_bo_in')->where($where)->field('id, name, desc')->select();
        return json(['status' => 200, 'msg' => $data]);
    }

    /*
     * 平台充值
     * shou_price           充值金额
     * shou_project_id      收款项目ID
     * shou_project_name    收款项目名称
     * shou_remark          备注
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function createShouOrder(){
        $shou_price = input('shou_price');
        $shou_pay_type = input('shou_pay_type') ?: 1;
        $shou_project_id = input('shou_project_id');
        $shou_project_name = input('shou_project_name');
        $shou_remark = input('shou_remark');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);
        if($shou_price <= 0) return json(['status' => 0, 'msg' => '金额不能为0']);

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);

        $user = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_invite, user_bo_invite_other, user_recharge_price')
            ->find();

        if($shou_project_id == 1){
            if($user['user_recharge_price'] != 0){
                return json(['status' => 100, 'msg' => '该用户已充值过首批款，请不要重复充值']);
            }
        }elseif($shou_project_id == 2 || $shou_project_id == 4){
            if($user['user_recharge_price'] == 0){
                return json(['status' => 100, 'msg' => '请先充值首批款']);
            }
        }

        if($shou_project_id == 1 || $shou_project_id == 2){
            if($user['user_invite'] != 'djl9988'){
                if(!$user['user_bo_invite_other']){
                    return json(['status' => 100, 'msg' => '请先绑定脖脸皮的上下级关系']);
                }
            }

            $upUser = Db::table('up_u_user')
                ->where('user_invite', $user['user_bo_invite_other'])
                ->field('user_bo_role, user_id')
                ->find();
            if($upUser['user_bo_role'] <= 2 && $upUser['user_id'] != config('company_xn_user')){
                return json(['status' => 100, 'msg' => '上级权限不足']);
            }
        }

        $number = 'SK_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);

        // todo：测试用
//        if($shou_project_id == 1){
//            if($shou_price == 0.01){
//                $shou_price1 = 19800;
//            }else{
//                $shou_price1 = 39800;
//            }
//        }else{
//            $shou_price1 = $shou_price * 10000;
//        }

        $insert = [
            'shou_number' => $number,
            'shou_user_id' => $this->user_id,
//            'shou_price' => $shou_price1,
            'shou_price' => $shou_price,
            'shou_pay_type' => $shou_pay_type,
            'shou_project_id' => $shou_project_id,
            'shou_project_name' => $shou_project_name,
            'shou_mchid' => $mchid['mch_id'],
            'shou_remark' => $shou_remark,
            'shou_time' => $this->create_time
        ];

        $wxConfig = config('wechat_servicer');
        $wxConfig['sub_mchid'] = $mchid['mch_code'];
        Db::startTrans();
        try{
            $shou_id = Db::table('up_shou')->insertGetId($insert);

            $wx = new Wxservicer($wxConfig);
            $return = $wx->WeChatPayReadyServicerV2($shou_price, $number, '款项');
            if($return['status'] == 200){
                Db::commit();
                return json(['status' => 200, 'msg' => $return['message'], 'shou_id' => $shou_id, 'price' => $shou_price]);
            }else{
                Db::rollback();
                return json(['status' => 0, 'msg' => $return['message']]);
            }
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /*
     * 子商户列表
     * start_time    筛选开始时间
     * end_time      筛选结束时间
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function mchidList(){
        $start_time = input('start_time');
        $end_time = input('end_time');
        $where['shou_is_pay'] = 2;

        if(!$start_time && !$end_time){
            $todayStart = date('Y-m-d 00:00:01');
            $where['shou_pay_time'] = ['>', $todayStart];
        }elseif ($start_time && !$end_time){
            $where['shou_pay_time'] = ['>', $start_time];
        }elseif (!$start_time && $end_time){
            $where['shou_pay_time'] = ['<', $end_time];
        }else{
            $where['shou_pay_time'] = ['BETWEEN', [$start_time, $end_time]];
        }
        $lists = Db::table('up_mchid')
            ->field('mch_id, mch_code, mch_default, mch_time, mch_status')
            ->order('mch_time desc')
            ->select();
        if($lists){
            $mx = Db::table('up_shou')->where($where)->field('shou_price, shou_mchid')->select();
            foreach ($lists as $k => $v){
                $total = 0;
                if($mx){
                    foreach ($mx as $kk => $vv){
                        if($vv['shou_mchid'] == $v['mch_id']){
                            $total += $vv['shou_price'];
                        }
                    }
                }
                $lists[$k]['total_price'] = $total;
            }
        }
        if($lists){
            return json(['status' => 200, 'msg' => $lists]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /*
     * 设置默认
     * mch_id    子商户ID
     * @return \think\response\Json
     */
    public function setDefault(){
        $mch_id = input('mch_id');

        Db::startTrans();
        try{
            Db::table('up_mchid')->where('mch_id', '<>', $mch_id)->update(['mch_default' => 2]);
            Db::table('up_mchid')->where('mch_id', $mch_id)->update(['mch_default' => 1]);

            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /*
     * 启用/禁用
     * mch_id    子商户号ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setStatus(){
        $mch_id = input('mch_id');
        $mch = Db::table('up_mchid')->where('mch_id', $mch_id)->field('mch_default, mch_status')->find();
        if($mch['mch_status'] == 1){
            if($mch['mch_default'] == 1) return json(['status' => 0, 'msg' => '默认收款商户号，不可以禁用']);
            $newStatus = 2;
        }else{
            $newStatus = 1;
        }
        $res = Db::table('up_mchid')->where('mch_id', $mch_id)->setField('mch_status', $newStatus);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 100, 'msg' => '操作失败']);
        }
    }

    /*
     * 收款明细
     * mchid                 子商户号
     * order_number          订单编号
     * other_order_number    第三方订单编号
     * user_username         用户名
     * user_phone            手机号
     * shou_project_id       收款项目ID
     * start_time            支付开始时间
     * end_time              支付结束时间
     * page                  页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shouList(){
        $mchid = input('mchid'); // 子商户号
        $order_number = input('order_number');
        $other_order_number = input('other_order_number');
        $user_username = input('user_username');
        $user_phone = input('user_phone');
        $shou_project_id = input('shou_project_id');
        $start_time = input('start_time');
        $end_time = input('end_time');

        $where['shou_is_pay'] = 2;

        if(isset($shou_project_id) && $shou_project_id != ''){
            $where['shou_project_id'] = $shou_project_id;
        }
        if(isset($mchid) && $mchid != ''){
            $where['mch_code'] = ['like', '%' . $mchid . '%'];
        }
        if(isset($order_number) && $order_number != ''){
            $where['shou_number'] = ['like', '%' . $order_number . '%'];
        }
        if(isset($other_order_number) && $other_order_number != ''){
            $where['shou_other_number'] = ['like', '%' . $other_order_number . '%'];
        }
        if(isset($user_username) && $user_username != ''){
            $where['user_username'] = ['like', '%' . $user_username . '%'];
        }
        if(isset($user_phone) && $user_phone != ''){
            $where['user_phone'] = ['like', '%' . $user_phone . '%'];
        }
        if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
            $where['shou_pay_time'] = ['between', [$start_time, $end_time]];
        }
        if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
            $where['shou_pay_time'] = ['>=', $start_time];
        }
        if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
            $where['shou_pay_time'] = ['<=', $end_time];
        }
        $lists = Db::table('up_shou')
            ->join('up_u_user', 'shou_user_id = user_id', 'LEFT')
            ->join('up_mchid', 'shou_mchid = mch_id', 'LEFT')
            ->field('shou_id, user_username, user_phone, mch_code, shou_number, shou_other_number, 
                shou_price, shou_project_name, shou_remark, shou_pay_time')
            ->where($where)
            ->order('shou_pay_time desc')
            ->page($this->page, 10)
            ->select();
        if($lists){
            return json(['status' => 200, 'msg' => $lists]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /*
     * 收款明细---用户看自己的
     * shou_project_id       收款项目ID
     * start_time            支付开始时间
     * end_time              支付结束时间
     * page                  页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userShouList(){
        $shou_project_id = input('shou_project_id');
        $start_time = input('start_time');
        $end_time = input('end_time');

        $where = ['shou_is_pay' => 2, 'shou_user_id' => $this->user_id];

        if(isset($shou_project_id) && $shou_project_id != ''){
            $where['shou_project_id'] = $shou_project_id;
        }
        if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
            $where['shou_pay_time'] = ['between', [$start_time, $end_time]];
        }
        if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
            $where['shou_pay_time'] = ['>=', $start_time];
        }
        if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
            $where['shou_pay_time'] = ['<=', $end_time];
        }
        $lists = Db::table('up_shou')
            ->join('up_mchid', 'shou_mchid = mch_id', 'LEFT')
            ->field('shou_id, shou_price, shou_project_name, shou_pay_time, shou_number, shou_remark')
            ->where($where)
            ->order('shou_pay_time desc')
            ->page($this->page, 10)
            ->select();
        if($lists){
            return json(['status' => 200, 'msg' => $lists]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
}